package com.liang.book.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liang.book.constant.Constant;
import com.liang.book.model.Result;
import com.liang.book.model.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor  {
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception {
        log.info("检验用户是否登录");
        HttpSession session = request.getSession();
        UserInfo userInfo = (UserInfo) session.getAttribute(Constant.USER_SESSION_KEY);
        if(userInfo == null) {
            //用户未登录
            log.warn("用户未登录");
            response.setStatus(401);
            response.setContentType("application/json;charset=utf-8");
            Result result = Result.fail("用户未登录");
            response.getOutputStream().write(objectMapper.writeValueAsString(result).getBytes());

//            response.getOutputStream().write("nologin".getBytes());
            return false;
        }
        log.info("用户登录成功");
        return true;//false拦截
    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        log.info("目标方法后执行代码");
//        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
//    }
//
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//         log.info("视图渲染完成后执行的代码");
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
//    }
}
